<template>
  <div class="unpaid">
    <div class="info-back search-part">
        <el-row :gutter="20">
            <el-col :span="12">
                <div class="back-icon" @click="back()">
                    <i class="fa fa-arrow-left" aria-hidden="true"></i>
                </div>
            </el-col>
        </el-row>
    </div>
    <div class="unpaid-goods">
      <v-unpaidgoodswf @transferGoodItem="getGoodItem"></v-unpaidgoodswf>
    </div>
      <div class="step-fixed"  v-show="isPayState == 0">
        <span>&nbsp;</span>
      </div>
      <div class="step3 tr">
          <div v-show="isPayState == 0">
              <div class="pd10 btns">
                  <span class="selected-title list-bottom-span">支付方式</span>
                  <el-select v-model="value" placeholder="现金" class="num-bottom-select" @change="changeWay()">
                      <el-option
                              v-for="item in options"
                              :key="item.value"
                              :label="item.label"
                              :value="item.value"
                              :disabled="item.disabled"
                      >
                      </el-option>
                  </el-select>
                  <span class="list-bottom-span">应收</span><el-input v-model="receivable" disabled class="num-bottom-input"></el-input>
                  <span class="list-bottom-span">实收</span>
                  <el-input v-model="received" v-if="disable" disabled class="num-bottom-input"></el-input>
                  <el-input v-model="received" v-else class="num-bottom-input"></el-input>
                  <el-button class="red-btn"  @click="settlement" v-show="isPayState == 0"> 结 算 </el-button>
              </div>
          </div>
      </div>

      <el-dialog
        title="提示"
        :visible.sync="dialogVisible"
        size="tiny"
        :before-close="handleClose">
        <span>正在支付，请稍后</span>
        <span slot="footer" class="dialog-footer">
          <!-- <el-button @click="dialogVisible = false">取 消</el-button> -->
          <el-button type="primary" @click="dialogVisible = false">确 定</el-button>
        </span>
      </el-dialog>

      <!--<el-dialog-->
        <!--title="提示"-->
        <!--:visible.sync="dialogVisible2"-->
        <!--size="tiny"-->
        <!--:before-close="handleClose2">-->
        <!--<span>支付成功</span>-->
        <!--<span slot="footer" class="dialog-footer">-->
          <!--&lt;!&ndash; <el-button @click="dialogVisible = false">取 消</el-button> &ndash;&gt;-->
          <!--<el-button type="primary" @click="dialogVisible = false">确 定</el-button>-->
        <!--</span>-->
      <!--</el-dialog>-->


  </div>
</template>
<script>
  import vUnpaidgoodswf from './UnpaidGoodsWf.vue';

    export default {
      name: 'keepAlive',
        components: {
          vUnpaidgoodswf
        },
        data: function () {
            return {
              received: 0.00,
              receivable: 0.00,
              options: [
                {
                  value: '20',
                  label: '现金',
                },
                {
                  value: '10',
                  label: '扣卡',
                  disabled: true
                },
                {
                  value: '40',
                  label: '代金券',
                  disabled: true
                },
                {
                  value: '30',
                  label: '积分',
                  disabled: true
                },
                {
                  value: '60',
                  label: '微信'
                },
                {
                  value: '70',
                  label: '支付宝'
                },
                {
                  value: '80',
                  label: '银行卡 '
                }
              ],
              value: '20',
              djqPrice: 0.00,
              selectedItems : '',
              isPayState: '',
              disable : false,
              dialogVisible: false,
              dialogVisible2: false,
            }
        },
        watch: {
          value(){
            if(this.value == 10 || this.value == 40 || this.value == 30){
              this.disable = true;
            }
            else {
              this.disable = false;
            }
          }
        },
        created(){
            this.$$("#content").scrollTop(0)
          console.log("123")
          console.log(this.$route.params.name);
          this.isPayState = this.$route.params.isPayState;
          console.log("=============>isPayState");
          this.showPayWay();
        },
        methods: {
          handleClose(done) {
             this.$confirm('确认关闭？')
               .then(_ => {
                //  done();
               })
               .catch(_ => {});
           },
//           handleClose2(done) {
//              this.$confirm('确认关闭？')
//                .then(_ => {
//                  // done();
//                  // this.back();
//                })
//                .catch(_ => {});
//            },
          back(){
            this.$router.push({
                path: '/cashierBill',
            });
          },
          getGoodItem(res){
            console.log(res);
            this.selectedItems = res;
            console.log(this.selectedItems);
            this.showJfWay();
          },
          showJfWay(){
            if(this.$route.params.name != undefined){
              //判断商品如果没有积分单价,积分禁用
              if(this.selectedItems){
                console.log("=========判断商品如果没有积分单价")
                this.selectedItems.forEach(item => {
                  console.log(item);
                  if(!item.score){
                    this.options[3].disabled = true;
                    return;
                  }
                });
              }


            }
              this.getGoodsLeft();
          },

          changeWay(){
            console.log(this.receivable);
            this.count();

          },
          count(){
            console.log(this.selectedItems)

            this.receivable = 0;
            this.received = 0;
            if(this.selectedItems.length != 0){
              this.selectedItems.forEach(item => {
                console.log(item.amount);
                this.receivable += parseFloat(item.amount);
              });
              this.receivable = Number(this.receivable).toFixed(2);
            }

            if(this.value == 10){   //扣卡
              console.log("=================>扣卡");
              if(this.selectedItems.length != 0){
                this.selectedItems.forEach(item => {
                  console.log(item.amount);
                  this.received +=parseFloat(item.memberPrice)*(item.quantity);

                });
              }
              this.received = Number(this.received).toFixed(2);
              console.log(this.receivable);
              console.log(this.received)
            }
            else if (this.value == 20 || this.value == 60 || this.value == 70 || this.value == 80) {  //现金
              if(this.selectedItems.length != 0){
                this.selectedItems.forEach(item => {
                  console.log(item.amount);
                  this.received += parseFloat(item.amount);
                });
                this.received = Number(this.received).toFixed(2);
              }
            }
            else if (this.value == 30) {   //积分
              if(this.selectedItems.length != 0){
                this.selectedItems.forEach(item => {
                  console.log(item.amount);
                  this.received = 0.00;
                });
              }

            }else if (this.value == 40) {    //代金券
              console.log(this.djqPrice);
              console.log(this.selectedItems)
              if(this.djqPrice == 0){
                if(this.selectedItems.length != 0){
                  this.selectedItems.forEach(item => {
                    console.log(item.amount);
                    this.received +=parseFloat(item.amount);
                  });
                  this.received = Number(this.received).toFixed(2);
                }

              }else {
                this.selectedItems.forEach(item => {
                  console.log(item.amount);
                  this.received +=parseFloat(this.djqPrice*item.goodsprice)*(item.quantity);
                });
                this.received = Number(this.received).toFixed(2);
              }
            }



          },

          showPayWay(){
            console.log(this.$route.params.name);
            if(this.$route.params.name != undefined){
              console.log("===================>会员");
              this.options[1].disabled = false;
              this.options[2].disabled = false;
              this.options[3].disabled = false;

              //是会员,默认为扣卡10
              this.value = "10";
            }else {
              this.options[1].disabled = true;
              this.options[2].disabled = true;
              this.options[3].disabled = true;
              //不是会员,默认为现金20
              this.value = "20";
            }

            this.getDjqLeft();     //根据该会员是否剩余代金券,看是否禁用代金券支付

          },

          getDjqLeft(){
            if(this.$route.params.memberId != undefined){
              let memberId = this.$route.params.memberId;
              // 计算该会员代金券的剩余量
              console.log("==========计算该会员代金券的剩余量");
              let self = this;
              this.$axioxs.get("/goods_paid/?userId=" + memberId + "&goodsId=3224b5f9-d073-40a9-8fbe-276b408c794e")
                 .then(function (res) {
                     console.log(res.data.records);
                     if(res.data.records.length != 0){    //
                       let djqQuantity = res.data.records[0].quantity;
                       let djqAmount = res.data.records[0].amount;
                       console.log(djqAmount)
                       if(djqQuantity == 0){
                         self.djqPrice = 0;    //否则显示原价
                         self.options[2].disabled = true;
                       }
                       else {        //如果该会员有剩余次数，则显示代金券的会员价格
                         console.log("================>代金券的会员价格")
                         self.djqPrice = djqAmount / djqQuantity;   //每张代金券的价钱
                         self.options[2].disabled = false;
                         console.log(self.djqPrice)
                       }
                     }else {
                       self.options[2].disabled = true;
                     }



                 })
                 .catch(function (error) {
                   console.log(error);
                   self.loading = true;
                 });
            }

            this.getJfLeft();      //根据该会员是否剩余积分,看是否禁用积分支付



          },
          getJfLeft(){
            // 计算该会员积分的剩余量
            if(this.$route.params.memberId != undefined){
              let memberId = this.$route.params.memberId;
              console.log("==========计算该会员积分的剩余量");
              let self = this;
              this.$axioxs.get("/goods_paid/?userId=" + memberId + "&goodsId=a7093a53-11d3-404c-bf3b-80ef7db398b5")
                 .then(function (res) {
                     console.log(res.data.records);
                     console.log(self.goodItem.score)
                     if(res.data.records.length != 0){   ////会员有剩余积分
                       let jfQuantity = res.data.records[0].quantity;
                       console.log("========jfQuantity"+ jfQuantity)
                       if(jfQuantity == 0 || !self.goodItem.score){       //商品剩余积分数量为0,积分方式禁用
                         console.log("===============>积分剩余为0")
                         self.options[3].disabled = true;
                       }else {
                         self.options[3].disabled = false;
                       }
                     }else {      ////会员无剩余积分,积分方式禁用
                        self.options[3].disabled = true;
                     }

                 })
                 .catch(function (error) {
                   console.log(error);
                   self.loading = true;
                 });
            }
          },

          getGoodsLeft(){
            if(this.$route.params.memberId != undefined){
              let oflag = {flag:false};
              for(let item of this.selectedItems){
                this.goodsLeft(item,oflag);
              }

            }
            console.log("////////////////////////")
            this.count();
          },
          goodsLeft(item,oflag){
            // 计算该会员已购商品数量
            console.log("==========计算该会员已购商品剩余量");
            console.log(item)
            let memberId = this.$route.params.memberId;
            let self = this;
            let isShow = true;
            console.log("/goods_paid/?userId=" + memberId + "&goodsId=" + item.goods_id)
            this.$axioxs.get("/goods_paid/?userId=" + memberId + "&goodsId=" + item.goods_id)
               .then(function (res) {
                   console.log(res.data.records);
                   if(res.data.records.length == 0){
                       console.log("================>会员已购没此商品")
                       oflag.flag = true;
                       self.options[1].disabled = true;
                       self.value = "20";
                   }
                   else {
                        console.log("================>会员已购有此商品")
                        if(!oflag.flag){
                          self.options[1].disabled = false;
                          self.value = "10";
                        }
                   }
               })
               .catch(function (error) {
                 console.log(error);
                 self.loading = true;
               });
               if(!isShow){
               return new Promise.reject('会员已购没此商品');
             }
          },
          settlement(){
            console.log(this.selectedItems);
            if(this.selectedItems.length == 0){
              this.$message({
                  showClose: true,
                  type: 'error',
                  message: "请至少选择一个商品!"
              });
              return;
            }
            let goodsIdArray = [];
            this.selectedItems.forEach(item => {
              console.log(item);
              goodsIdArray.push(item.id);
            });
            console.log(goodsIdArray);
            console.log(goodsIdArray.join(","))

            var data = {
              "receivable": this.receivable,
              "received": this.received,
              "entriesId": goodsIdArray.join(","),
              "payment": this.value,
              "id": this.$route.params.sn,
              "state": "1",
              "remark":"完成"
            };
            console.log(JSON.stringify(data));
            this.dialogVisible = true;
            let self = this;
            this.$axioxs.post("/sale/entry", this.$qs.stringify(data))
              .then(function () {
                      self.$message({
                          showClose: true,
                          type: 'success',
                          message: '结算成功'
                      });
                      self.$router.push("/cashierBill");
                      console.log("==============>success");
                      self.dialogVisible = false
                  },
                  (res) => {
                  console.log(res)
                      self.$message({
                          showClose: true,
                          type: 'error',
                          message: res
                      });
                  })
            }

          }

    }

</script>

<style scoped>
.fr{
    float: right;
}
.pay-way label{
  display: inline-block;
  text-align: right;
  padding: 0px 6px 0px 15px;
}
.pay-way{
  padding: 0 6px 10px 0px;
}
.step-fixed {
    position: fixed;
    bottom: 0;
    padding-top: 20px;
    padding-bottom: 20px;
    background: #fff;
    z-index: 999;
    width: 100%;

}
.form{
  width: 75%
}
.settlement{
  margin-left: 80%;
}
.unpaid-goods{
  padding-top: 60px;
}
.selected-result .result{
  margin: 5px;
}
.el-input {
    position: relative;
    font-size: 14px;
    display: inline-block;
}
.list-bottom-span{
    color: #fff;
}
.num-bottom-input{
    width: 13%;
}
.num-bottom-select{
    width: 11%;
}

.step-fixed {
    width: 100%;
    position: fixed;
    bottom: 0;
    padding-top: 20px;
    padding-bottom: 20px;
    background: #000;
    opacity: 0.6;
    z-index: 3;
}

.step-fixed button{
    margin-left: 30px;
}
</style>
